package org.onvivals.app.modules.auth.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.onvivals.app.modules.auth.param.LoginParam;
import org.onvivals.common.enums.AppFromEnum;
import org.onvivals.common.exception.BusinessException;
import org.onvivals.common.utils.IpUtil;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.entity.dto.WechatUserDto;
import org.onvivals.module.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登陆认证服务类
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthService {

	private final IUmsUserService umsUserService;
	private final WxMaService wxMaService;

	/**
	 * 小程序登陆
	 *
	 * @param loginParam loginParam
	 * @return long
	 */
	public UmsUser wxappLogin(LoginParam loginParam) {
		String code = loginParam.getCode();
		String encryptedData = loginParam.getEncryptedData();
		String iv = loginParam.getIv();
		try {
			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
			WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService()
					.getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
			UmsUser member = this.umsUserService.getOne(Wrappers.<UmsUser>lambdaQuery()
					.eq(UmsUser::getPhone, phoneNoInfo.getPhoneNumber()), false);
			if (ObjectUtil.isNull(member)) {
				//过滤掉表情
				String ip = IpUtil.getRequestIp();
				member = UmsUser.builder()
						.username(phoneNoInfo.getPhoneNumber())
						.phone(phoneNoInfo.getPhoneNumber())
						.addIp(ip)
						.lastIp(ip)
						.nickname(phoneNoInfo.getPhoneNumber())
						.userType(AppFromEnum.ROUNTINE.getValue())
						.build();
				//构建微信用户
				WechatUserDto wechatUserDTO = WechatUserDto.builder()
						.routineOpenid(session.getOpenid())
						.unionId(session.getUnionid())
						.build();
				member.setWxProfile(wechatUserDTO);
				umsUserService.save(member);
			} else {
				WechatUserDto wechatUser = member.getWxProfile();
				if (null != wechatUser && (StrUtil.isBlank(wechatUser.getRoutineOpenid()) && StrUtil.isNotBlank(session.getOpenid()))) {
					wechatUser.setRoutineOpenid(session.getOpenid());
					member.setWxProfile(wechatUser);
				}
				member.setUserType(AppFromEnum.ROUNTINE.getValue());
				this.umsUserService.updateById(member);
			}
			return member;
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new BusinessException(e.toString());
		}
	}
}
